package com.jsnkj.basic.photo

import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.jsnkj.basic.bean.PhotoBean
import com.jsnkj.basic.mvvm.HttpViewModel
import com.jsnkj.basic.util.DateUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *
 * @功能描述:
 * @创建时间:     2021/12/31
 * @创建者:       阳
 * @修改时间:     2021/12/31
 * @修改者:       阳
 */
class PuzzlePhotoItemMVVMViewModel : HttpViewModel() {

    /**
     * 照片路径列表，包含照片的日期
     */
    var photoList: ArrayList<Any> = ArrayList()// 图片列表数据
    val photoLoading: MutableLiveData<Boolean> = MutableLiveData()// 图片数据变化标记

    var offset = 0// 每次加载图片的起始位置
    private val limit = 1000// 每次加载图片数量
    var hasPhoto = true// 是否还有照片

    /**
     * 检索系统图片
     * @param demoList 样本图片
     */
    fun loadPhoto(context: Context, demoList: ArrayList<PhotoBean> = ArrayList()) {
        if (!hasPhoto) {
            return
        }

        photoLoading.value = false
        viewModelScope.launch(Dispatchers.IO) {

            // 构造SQL分页查询，不能直接拼接SQL（拼接SQL在高版本Android被禁止）
            // 参考：https://www.codenong.com/js559601235819/

            // 从数据库检索图片数据出来
            val query = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                val queryArgs = Bundle()
                queryArgs.putString(
                    ContentResolver.QUERY_ARG_SQL_SORT_ORDER,
                    "${MediaStore.Images.Media.DATE_MODIFIED} desc"
                )
                queryArgs.putString(ContentResolver.QUERY_ARG_SQL_LIMIT, "$limit offset $offset")

                context.contentResolver.query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    null, queryArgs, null
                )
            } else {
                context.contentResolver.query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    null,
                    null,
                    null,
                    "${MediaStore.Images.Media.DATE_MODIFIED} desc limit $limit offset $offset"
                )
            }

            // 首次加载图片时的处理
            if (0 == offset) {

                // 清空图片数据
                photoList.clear()

                // 首先加入图片样例数据
                if (demoList.size > 0) {
                    photoList.addAll(demoList)
                }
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                query?.use {
                    val idColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
                    val dateColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED)
                    val pathColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)

                    var lastDate = ""
                    while (it.moveToNext()) {
                        // Get values of columns for a given video.
                        val imageId = it.getLong(idColumn)
                        val date = it.getLong(dateColumn)
                        val path = it.getString(pathColumn)
                        val uri: Uri =
                            ContentUris.withAppendedId(
                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                imageId
                            )

                        val curDate = DateUtil.getDate(date * 1000)

                        if (lastDate != curDate) {
                            photoList.add(curDate)
                        }

                        val bean = PhotoBean(uri, curDate, imageId, context.contentResolver, path)
                        photoList.add(bean)
                        lastDate = curDate
                    }

                    // 更新下次查询的起始位置
                    offset += it.count

                    // 判断是否还有图片数据
                    hasPhoto = limit == it.count

                    withContext(Dispatchers.Main) {
                        photoLoading.value = true
                    }
                }
            }
        }
    }
}